<?php

namespace addons\cms\controller\api;

use addons\alioss\Alioss;
use addons\cms\model\ArchivesInteraction;
use addons\cms\model\Notice;
use addons\cms\model\SocietiesSign;
use addons\qrcode\library\Service;
use addons\third\model\Third;
use app\admin\model\cms\ActivitySign;
use app\common\model\cms\Delivery;
use app\common\model\user\Level;
use OSS\OssClient;
use think\Cache;
use think\Config;
use think\Exception;
use think\Response;
use think\Validate;

/**
 * 会员
 */
class User extends Base
{
    protected $noNeedLogin = ['getSigned', 'userInfo'];

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 个人中心
     */
    public function index()
    {
//        $apptype = $this->request->param('apptype');
//        $platform = $this->request->param('platform');
//        $logincode = $this->request->param('logincode');
//        $user = \addons\cms\model\User::select();
//        $societies = new \addons\cms\model\Societies();
//        foreach ($user as $index => $datum){
//            $datum->societies_no = $societies->memberCode(8);
//            $datum->save();
//        }
//        dd(1);
        $info = $this->auth->getUserInfo();
//        dd($info);
        unset($info['nickname'], $info['level'], $info['token'], $info['money'],$info['bio']);
//        $info['avatar'] = cdnurl($info['avatar'], true);
        if (!empty($info['birthday']) && $info['birthday'] == '0000-00-00'){
            $info['birthday'] = '';
        }
        $level_info = Level::where('id', $info['level_id'])->field('id,name,name_zh_cn,name_en,up_sign_activity,background_image')->find();
        if($level_info['background_image']){
            $level_info['background_image'] = cdnurl($level_info['background_image'], true);
        }
        $lang = getHeaderLang();
        if ($lang != getDefaultLang()) {
            $level_info['name'] = $level_info['name_'.$lang];
        }

        $info['level_info'] = $level_info;
        $info['delivery_info'] = Delivery::where('user_id', $info['id'])->field('id,delivery,delivery_num,delivery_company,delivery_time,status,qrcode,finish_time')->find() ?? '';
//        $vip = get_addon_info('vip');
//        $info['is_install_vip'] = ($vip && $vip['state']);
//        if (!$info['is_install_vip']) { //禁用
//            $info['vip'] = 0;
//            $info['vipInfo'] = null;
//        } else {
//            $info['vipInfo'] = \addons\vip\library\Service::getVipInfo($info['id']) ?? null;
//            if (empty($info['vipInfo'])) {
//                $info['vip'] = 0;
//            }
//        }
//        $signin = get_addon_info('signin');
//        $info['is_install_signin'] = ($signin && $signin['state']);

        $firstlogin = $this->auth->jointime === $this->auth->logintime;

        $info['societies'] = [];
        if ($info['is_societies'] == 1){
            $info['societies'] = SocietiesSign::where('user_id', $info['id'])->field('name,mobile,gender,user_address,email')->find();
        }
        $info['notice_total'] = Notice::where('user_id', $info['id'])->where('status','unread')->count() ?? 0;

        //判断是否显示昵称更新提示
//        $profilePrompt = false;
//        $config = get_addon_config('cms');
//        if ($config['porfilePrompt'] === 'firstlogin') {
//            $profilePrompt = $this->auth->jointime === $this->auth->logintime;
//        } elseif ($config['porfilePrompt'] === 'everylogin') {
//            $profilePrompt = true;
//        } elseif ($config['porfilePrompt'] === 'disabled') {
//            $profilePrompt = false;
//        }
//        $showProfilePrompt = false;
//        if ($profilePrompt) {
//            $showProfilePrompt = !$info['nickname'] || stripos($info['nickname'], '微信用户') !== false || preg_match("/^\d{3}\*{4}\d{4}$/", $info['nickname']);
//        }
//
//        $openid = '';
//        //如果有传登录code，则获取openid
//        if ($logincode) {
//            $json = (new \addons\cms\library\Wechat\Service())->getWechatSession($logincode);
//            $openid = $json['openid'] ?? '';
//        }
//        $data['openid'] = $openid;

        //

        $this->success('', [
            'userInfo' => $info,
//            'openid'            => $openid,
//            'showProfilePrompt' => $showProfilePrompt
        ]);
    }

    public function member_qrcode()
    {
        $config = get_addon_config('qrcode');
        $user_id = $this->auth->id;
        $user = \app\common\model\User::field('id,nickname,bio,score,avatar,status,is_societies,societies_no,qrcode')->where('id', $user_id)->find();
        if (!$user) {
            $this->error("未找到指定会员");
        }
        if ($user['status'] == 'hidden') {
            $this->error("暂时无法浏览");
        }

        $member_code = $user['societies_no'];

        $sign_code = $member_code.'_'.rand(10000, 99999);
        $data = [
            'code' => $member_code,
            'type' => 'user'
        ];
        $cache_qrcode = Cache::get('user_'.$member_code.'_qrcode');
        if ($user->qrcode) {
            $this->success('', [
                'qrcode' => $user->qrcode,
                'code' => $member_code,
                'score' => $user['score'],
            ]);
        }
        $http_build_query_data = http_build_query($data);
        $qrCode = Service::qrcode([
            'text' => $http_build_query_data
        ]);

        $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';
        $response = Response::create()->header("Content-Type", $mimetype);

        // 直接显示二维码
        header('Content-Type: ' . $qrCode->getContentType());
        $response->content($qrCode->writeString());

        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }

        $qrcode_path = '';
        if (is_really_writable($qrcodePath)) {
            $fileName = md5(implode('', ['text' => $http_build_query_data])). '.'. $config['format'];
            $aly_oss_config = get_addon_config('alioss');
            $filePath = $qrcodePath . $fileName;
            $qrCode->writeFile($filePath);

            try {
                $alioss = new OssClient($aly_oss_config['accessKeyId'], $aly_oss_config['accessKeySecret'], $aly_oss_config['endpoint']);
                $res = $alioss->uploadFile($aly_oss_config['bucket'],$fileName,$filePath);
                $qrcode_path = $res['info']['url'];
                Cache::set('user_'.$user_id.'_qrcode', $qrcode_path, 86400); //缓存300秒(5分钟)
                Cache::set('user_'.$user_id.'_code', $sign_code, 86400); //缓存300秒(5分钟)
                $user->qrcode = $qrcode_path;
                $user->save();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        }

        $this->success('', [
            'qrcode' => $qrcode_path,
            'societies_no' => $member_code,
            'score' => $user['score'],
        ]);
//        $qrcode->setData($member_code);
    }
    //用户发表的文章和评论
    public function userInfo()
    {

        $user_id = $this->auth->id;
        $type = $this->request->param('type');
        $user = \app\common\model\User::field('id,nickname,bio,avatar,status')->where('id', $user_id)->find();
        if (!$user) {
            $this->error("未找到指定会员");
        }
        if ($user['status'] == 'hidden') {
            $this->error("暂时无法浏览");
        }
        $user['avatar'] = cdnurl($user['avatar'], true);
        $pagesize = 10;
        $data = ['user' => $user];
        if ($type == 'archives') {
            $data['list'] = \addons\cms\model\Archives::with([
                'user' => function ($query) {
                    $query->field('id,nickname,avatar');
                },
                'channel'
            ])
                ->where('user_id', $user['id'])
                ->field('id,user_id,title,channel_id,dislikes,likes,tags,createtime,image,images,style,comments,views,diyname')
                ->where('status', 'normal')
                ->order('id', 'desc')
                ->paginate($pagesize);
            foreach ($data['list'] as $index => $datum) {
                $datum['id'] = $datum['eid'];
            }
        } else {
            $commentList = \addons\cms\model\Comment::with([
                'user' => function ($query) {
                    $query->field('id,nickname,avatar');
                },
                'archives'
            ])
                ->where('type', 'archives')
                ->where('user_id', $user['id'])
                ->where('status', 'normal')
                ->order('id', 'desc')
                ->paginate($pagesize);
            foreach ($commentList as $index => $item) {
                $item->create_date = human_date($item->createtime);
                if ($item->archives) {
                    $item->aid = $item->archives->eid;
                    $item->archives->eid = $item->archives->eid;
                }
            }
            $commentList = $commentList->toArray();

            foreach ($commentList['data'] as $index => &$datum) {
                if (isset($datum['archives']) && $datum['archives']) {
                    $datum['archives']['id'] = $datum['archives']['eid'];
                    unset($datum['archives']['channel']);
                }
            }
            $data['list'] = $commentList;
        }
        $data['archives'] = \addons\cms\model\Archives::where('user_id', $user['id'])->where('status', 'normal')->count();
        $data['comments'] = \addons\cms\model\Comment::where('user_id', $user['id'])->where('status', 'normal')->count();
        $this->success('', $data);
    }

    public function my_comment()
    {
        $user_id = $this->auth->id;
        $type = $this->request->param('type');
        $user = \app\common\model\User::field('id,username,bio,avatar,status')->where('id', $user_id)->find();
        if (!$user) {
            $this->error("未找到指定会员");
        }

        $commentList = \addons\cms\model\Comment::with([
            'user' => function ($query) {
                $query->field('id,username,avatar');
            }
        ])
            ->where('type', $type)
            ->where('user_id', $user['id'])
            ->where('status', 'normal')
            ->order('id', 'desc')
            ->field('id,user_id,type,aid,content,ip_address,createtime')
//            ->select();
            ->paginate(10);
        $lang = getHeaderLang();
        foreach ($commentList as $index => $item) {
            switch ($item['type']){
                case 'archives':
                    $item->info = \addons\cms\model\Archives::where('id', $item['aid'])->field('id,title,title_zh_cn,title_en,channel_id,image')->find();
                    if ($lang!= getDefaultLang()) {
                        $item->info->title = $item->info['title_'.$lang];
                    }
                    break;
                case 'activity':
                    $item->info = \addons\cms\model\Activity::where('id', $item['aid'])->field('id,title,title_zh_cn,title_en,image')->find();
                    if ($lang!= getDefaultLang()) {
                        $item->info->title = $item->info['title_'.$lang];
                    }
                    break;
            }
            if (!$item['info']) {
                unset($commentList[$index]);
            }
//            $item->create_date = human_date($item->createtime);
            $item->create_date_text = date('m-d',$item->createtime);
        }
//        $commentList = $commentList->toArray();

//        foreach ($commentList['data'] as $index => &$datum) {
//            if (isset($datum['archives']) && $datum['archives']) {
//                $datum['archives']['id'] = $datum['archives']['eid'];
//                unset($datum['archives']['channel']);
//            }
//        }
        $data = $commentList->toArray();
        $this->success('', $data);
    }
    /**
     * 个人资料
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $gender = $this->request->post('gender');
        $birthday = $this->request->post('birthday');
        $avatar = $this->request->post('avatar');
        $province = $this->request->post('province');
        $city = $this->request->post('city');
        $district = $this->request->post('district');
        $guardian_name = $this->request->post('guardian_name');
        $guardian_phone = $this->request->post('guardian_phone');
        if (!$username) {
            $this->error("Usernames and nicknames cannot be empty");
        }

        $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
        if ($exists) {
            $this->error('Username already exists');
        }
        $user->username = $username;
        $user->gender = $gender;
        $user->birthday = $birthday;
        $user->avatar = $avatar;
        if ($province){
            $user->province = $province;
        }
        if ($city){
            $user->city = $city;
        }
        if ($district){
            $user->district = $district;
        }
        $age = $this->calculateAge($birthday);
        if ($age <6){
            $this->error('If you are under the age of 6, please register again when you are younger');
        }
        if ($age < 18 && (empty($guardian_name) || empty($guardian_phone))){
            $this->error("Please fill in the guardian's information");
        }
        if ($guardian_name){
            $user->guardian = $guardian_name;
        }
        if ($guardian_phone){
            $user->guardian_phone = $guardian_phone;
        }
        $user->save();
        $this->success('modification was successful！');
    }

    function calculateAge($input) {
        // 检查输入格式是否为 "YYYY-MM"
//        if (!preg_match('/^\d{4}-\d{1,2}$/', $input)) {
//            return false;
//        }

        // 分割年月并补足月份为两位数
//        list($year, $month) = explode('-', $input);
//        $month = str_pad($month, 2, '0', STR_PAD_LEFT);
        $birthdayStr = $input; // 假设为当月第一天

        // 创建日期对象
        try {
            $birthDate = new \DateTime($birthdayStr);
            $currentDate = new \DateTime();
        } catch (Exception $e) {
            $this->error('date format error');
        }

        // 检查生日是否在未来
        if ($birthDate > $currentDate) {
            $this->error('date format error');
        }

        // 计算年龄
        $interval = $currentDate->diff($birthDate);
        return $interval->y;
    }
    /**
     * 保存头像
     */
    public function avatar()
    {
        $user = $this->auth->getUser();
        $avatar = $this->request->post('avatar');
        if (!$avatar) {
            $this->error("The avatar cannot be empty");
        }

        $avatar = str_replace(cdnurl('', true), '', $avatar);
        $user->avatar = $avatar;
        $user->save();
        $this->success('The modification was successful！');
    }

    public function notice()
    {
        $user_id = $this->auth->id;
        $user = Notice::where('user_id', $user_id)->field('id,title,content,status,createtime')->order('id desc')->paginate(10);
        Notice::where('user_id', $user_id)->where('status','unread')->update(['status' => 'read']);
        $this->success('', $user);
    }

    public function batch_notice()
    {
        $user_id = $this->auth->id;
        $ids = $this->request->post('ids');
        $user = Notice::where('user_id', $user_id)->where('id','in',$ids)->update(['status' => 'read']);

        $this->success('', $user);
    }
    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'), ['__token__' => $this->request->token()]);
    }

    /**
     * 公众号内分享
     */
    public function getSigned()
    {
        $url = $this->request->param('url', '', 'trim');
        $js_sdk = new \addons\cms\library\Jssdk();
        $data = $js_sdk->getSignedPackage($url);
        $this->success('', $data);
    }

    /**
     * @return void
     * @throws \think\exception\DbException
     * 点赞列表
     */
    public function like_list()
    {
        $collection = new ArchivesInteraction();
        $type = $this->request->param('type');

        $user_id = $this->auth->id;
        $collectionList = $collection->where('user_id', $user_id)
            ->where('type', $type)
            ->order('id', 'desc')
//            ->select();
            ->paginate(10);
        $new_data = [];
        $lang = getHeaderLang();
        foreach ($collectionList as $index => $item) {
            if ($item['type'] == 'activity') {
                $item->info = \addons\cms\model\Activity::where('status', 'normal')
                    ->where('id',$item->aid)
                    ->field('updatetime,deletetime',true)
                    ->find();
                if ($lang!= getDefaultLang()) {
                    $item->info->title = $item->info['title_'.$lang];
//                    $item->info->description = $item->info['description_'.$lang];
                }
                $is_like = $is_collection = 0;
                if ($this->auth->id){
                    if (ArchivesInteraction::where(['user_id'=>$this->auth->id,'aid'=>$item->aid,'type' => 'activity'])->find()){
                        $is_like = 1;
                    }
                    if(\addons\cms\model\Collection::where(['user_id' => $this->auth->id,'aid' => $item->aid,'type' => 'activity'])->find()){
                        $is_collection = 1;
                    }
                }
                $sign = ActivitySign::where(['user_id'=> $this->auth->id,'activity_id'=>$item->aid])->find();
                $item->info->is_sign = $sign ? 1 : 0;
                $item->info->sign_num = ActivitySign::where('activity_id',$item->aid)->count();
                $item->info->sign_remaining = $item->info->attend_num - $item->info->sign_num;
                $item->info->is_like = $is_like;
                $item->info->is_collection = $is_collection;
                if (!$item->info) {
                    continue;
                }
                $new_data[] = $item->info;
            }else{
                $info = \addons\cms\model\Archives::where('status', 'normal')
                    ->where('id',$item->aid)
                    ->field('id,channel_id,user_id,title,title_zh_cn,title_en,description,image,createtime,views,likes,comments,dislikes,author,author_zh_cn,author_en')
                    ->find();

                if ($lang!= getDefaultLang()) {
                    $info->title = $info['title_'.$lang];
//                    $info->description = $info['description_'.$lang];
                }
                $is_like = $is_collection = 0;
                if ($this->auth->id){
                    if (ArchivesInteraction::where(['user_id'=>$this->auth->id,'aid'=>$item->aid,'type' => 'archives'])->find()){
                        $is_like = 1;
                    }
                    if(\addons\cms\model\Collection::where(['user_id' => $this->auth->id,'aid' => $item->aid,'type' => 'archives'])->find()){
                        $is_collection = 1;
                    }
                }

                $info['is_like'] = $is_like;
                $info['is_collection'] = $is_collection;
                $item->info = $info;
//                $item->info->is_like = $is_like;
//                $item->info->is_collection = $is_collection;
                if (!$item->info) {
                    continue;
                }
                $new_data[] = $item->info;
            }
        }
        $collectionList = $collectionList->toArray();
        $collectionList['data'] = $new_data;
//        dd($collectionList);
        $this->success('获取成功', $collectionList);
    }
}
